/**
 * 定义OnlineMonitorController在线监测管理模块
 */
(function(window, angular, undefined){
	var SearchPanelController = angular.module('SearchPanelController', ['ui.router','itfreer','waterCommon']);
	
	//污染源：统一的污水处理厂列表控制器，污染源信息，报警信息，设备资产管理，运营管理，远程控制等模块使用
	SearchPanelController.controller('WsclcSearchController',function($sce,$scope,$itfreerHttp,$itfreer,$compile,
			$http,$waterDataCommon,$httpData,$queryObj,$wdp,$rootScope,$state,$formObject){
		$queryObj.QueryWsclcObj={"NAME":"","Exp_No":""};
		//去掉视频延迟函数
		if($wdp.timeout){
			clearTimeout($wdp.timeout); 
		}
		$wdp.viewValue.wwtpDetailParm = {};
		$queryObj.QueryWsclcObj.pollType=getWaterType();
		//查询污水处理厂列表
		$scope.queryList=function(){
			 $waterDataCommon.getPageRows("/OnlineMonitor/wsclc.do","WsclcList",$queryObj.QueryWsclcObj,8,1,function(data){
				 if(data.data.length > 0){
					 for(var i in data.data){
						 var item = data.data[i];
						 var mns = item.MNS;
						 var inMN = $scope.getMN(mns,"0");
						 var outMN = $scope.getMN(mns,"1");
						 data.data[i]["MN0"] = inMN;
						 data.data[i]["MN1"] = outMN;
						 
						 var scs = item.SCS;
						 var inSC = $scope.getStationId(scs,"0");
						 var outSC = $scope.getStationId(scs,"1");
						 data.data[i]["SC0"] = inSC;
						 data.data[i]["SC1"] = outSC;
					 }
				 }
				 updateWWTPParm(data);
			 });
		};
		
		function updateWWTPParm(data){
		/*	var stationArray=[];
			for(var i=0; i<data.data.length;i++){
				var item=data.data[i];
				if(item.IMG){
					var imgUrl=item.IMG.split(':')[0].split('/');
					var str=imgUrl[imgUrl.length-1];
					item.smallImg="/WaterMonitor/temp/upload/plupload/pic_temp/temp"+str;
				}
				else{
					item.smallImg="";
				}
				stationArray.push(item);
			}
			 data.data=stationArray;*/
			 $wdp.viewValue.wsclcList = data;
			 if(data.data.length > 0){
				 $scope.selectWWTP(data.data[0]);
			 }
		}
		
		//选择某个污水处理厂
		$scope.selectWWTP = function(curRow){
			$wdp.viewValue.wwtpDetailParm = {
					WWTPID:curRow.SDEEXP_NO,
					WWTP_NAME:curRow.SDENAME,
					MN0:curRow.MN0,
					MN1:curRow.MN1,
					SC0:curRow.SC0,
					SC1:curRow.SC1};
			$scope.WWTP_ID = curRow.SDEEXP_NO;
			$scope.$emit('dataPramChange', {WWTPID:curRow.SDEEXP_NO}); 
		};
		
		// 获取设备在线状态
		$scope.getOnlineInfo = function(stationInfoStr,flowType){
			if(stationInfoStr == null || stationInfoStr == ""){
				return 0;
			}
			var stationInfos = stationInfoStr.split(",");
			for(var i =0;i<stationInfos.length;i++){
				if(stationInfos[i] == "ft"+flowType+"_s1"){
					return 1;
				}
			}
			return 0;
		}
		
		// 获取设备编号
		$scope.getMN = function(stationInfoStr,flowType){
			if(stationInfoStr == null || stationInfoStr == ""){
				return null;
			}
			var stationInfos = stationInfoStr.split(",");
			for(var i =0;i<stationInfos.length;i++){
				var item = stationInfos[i];
				if(item.indexOf("ft"+flowType) > -1){
					var mn = item.replace("ft"+flowType+"_mn","");
					return mn;
				}
			}
			return null;
		}
		
		// 获取站点编号
		$scope.getStationId = function(stationInfoStr,flowType){
			if(stationInfoStr == null || stationInfoStr == ""){
				return null;
			}
			var stationInfos = stationInfoStr.split(",");
			for(var i =0;i<stationInfos.length;i++){
				var item = stationInfos[i];
				if(item.indexOf("ft"+flowType) > -1){
					var mn = item.replace("ft"+flowType+"_sc","");
					return mn;
				}
			}
			return null;
		}
		
		//在地图上显示
		$scope.showInMap=function(data){
			$itfreer_arcgis_map.setServices("PS_WWTPM",true);
			$.ajax({
				url:getBasePath() + "/OnlineMonitor/getGeoByid.do?EXP_NO="+data.SDEEXP_NO,
				dataType : 'json',
				success:function(d){
					$waterDataCommon.AddWktFeaturesToMap(d,null,function(graphic){
						$scope.safeApply(function(){
							$wdp.viewValue.path=d.data[0];
						});
					},true);
				}
			});
			$formObject.isMIS = false;
			$wdp.viewValue.showBackToMisBtn = true;
			setTimeout(function() {
				$wdp.widowResizeEventHandler();
			}, 200);
		};
		
		if($wdp.viewValue.wsclcList != null && $wdp.viewValue.wsclcList.data != null && $wdp.viewValue.wsclcList.data.length > 0){
			$httpData.WsclcList = $wdp.viewValue.wsclcList;
			updateWWTPParm($httpData.WsclcList);
		}
		else{
			$scope.queryList();
		}
		$scope.waterDataCommon = $waterDataCommon;
	});
	
	//污染源：实时数据，历史数据，报表模块的污水处理厂列表控制器，与WsclcSearchController相比，多了污水参数部分
	SearchPanelController.controller('WWTPListController',function($sce,$scope,$itfreerHttp,$itfreer,$compile,$http,$waterDataCommon,$httpData,$queryObj,$wdp,$rootScope,$state,$formObject){
		
		$queryObj.QueryWsclcObj={};
		$scope.wwtplist = {};
		
		var pollUnit_realTime = {
			"011":"mg/L",
			"060":"mg/L",
			"B01":"m³/h",
			"B01TOTAL":"m³",
			"001":"",
			"101":"mg/L"
		};
		
		var pollUnit_report = {
			"011":"kg",
			"060":"kg",
			"B01":"",
			"B01TOTAL":"m³",
			"001":"",
			"101":"kg"
		};
		
		$scope.parmListShow = false;
		
		$scope.queryList=function(){
			 $waterDataCommon.getPageRows("/OnlineMonitor/wsclc.do","WsclcList",$queryObj.QueryWsclcObj,8,1,function(data){
				 if(data.data.length > 0){
					 for(var i in data.data){
						 var item = data.data[i];
						 var mns = item.MNS;
						 var inMN = $scope.getMN(mns,"0");
						 var outMN = $scope.getMN(mns,"1");
						 data.data[i]["MN0"] = inMN;
						 data.data[i]["MN1"] = outMN;
						 
						 var scs = item.SCS;
						 var inSC = $scope.getStationId(scs,"0");
						 var outSC = $scope.getStationId(scs,"1");
						 data.data[i]["SC0"] = inSC;
						 data.data[i]["SC1"] = outSC;
					 }
				 }
				 $scope.selectWWTP = data.data[0];
				 noticeParmChange();
				// 前端缓存列表信息
				 $wdp.viewValue.wsclcList = data;
			 });
		};
		
		// 污水厂列表更新后，更新参数信息
		function updateWWTPParm(data){
			 var wwtpInfo = {
						 WWTPID:data.SDEEXP_NO,
						 WWTP_NAME:data.SDENAME,
						 MN0:data.MN0,
						 MN1:data.MN1,
						 SC0:data.SC0,
						 SC1:data.SC1
					 };
			 var reportParms = getReportParms();
			 $wdp.viewValue.wwtpReportParm = angular.extend(wwtpInfo,reportParms);
		}
		
		// 获取在线信息
		$scope.getOnlineInfo = function(stationInfoStr,flowType){
			if(stationInfoStr == null || stationInfoStr == ""){
				return 0;
			}
			var stationInfos = stationInfoStr.split(",");
			for(var i =0;i<stationInfos.length;i++){
				if(stationInfos[i] == "ft"+flowType+"_s1"){
					return 1;
				}
			}
			return 0;
		}
		
		// 获取设备编号
		$scope.getMN = function(stationInfoStr,flowType){
			if(stationInfoStr == null || stationInfoStr == ""){
				return null;
			}
			var stationInfos = stationInfoStr.split(",");
			for(var i =0;i<stationInfos.length;i++){
				var item = stationInfos[i];
				if(item.indexOf("ft"+flowType) > -1){
					var mn = item.replace("ft"+flowType+"_mn","");
					return mn;
				}
			}
			return null;
		}
		
		// 获取站点编号
		$scope.getStationId = function(stationInfoStr,flowType){
			if(stationInfoStr == null || stationInfoStr == ""){
				return null;
			}
			var stationInfos = stationInfoStr.split(",");
			for(var i =0;i<stationInfos.length;i++){
				var item = stationInfos[i];
				if(item.indexOf("ft"+flowType) > -1){
					var mn = item.replace("ft"+flowType+"_sc","");
					return mn;
				}
			}
			return null;
		}
		
		// 获取表头参数
		function getReportParms(){
			$("inpug[name='vocParma']").removeAttr("checked");
			var parmToCheckDom = $("input[name='parmToCheck']:checked");
			var parmToChecksStr = "";
			var parmToCheckList = [];
			var unit= {};
			var isStatistics = false;
			if($state.current.name.indexOf("statistics") > -1){
				unit = pollUnit_report;
				isStatistics = true;
			}
			else{
				unit = pollUnit_realTime;
			}
			
			for(var i=0;i<parmToCheckDom.length;i++){
				var parmName = $(parmToCheckDom[i]).val();
				var parmText = $(parmToCheckDom[i]).attr("parmText");
				
				if(isStatistics && parmName == "B01"){
					continue;
				}
				
				var unitText = unit[parmName];
				if(unitText){
					unitText = parmText +(isStatistics && (parmName != "B01"&& parmName != "B01TOTAL")?"排放量":"")+ "(" + unitText + ")";
				}
				else{
					unitText = parmText;
				}
				
				var couText = pollUnit_report[parmName];
				if(couText){
					couText = parmText +((parmName != "B01"&& parmName != "B01TOTAL")?"排放量":"")+ "(" + couText + ")";
				}
				else{
					couText = parmText;
				}
				
				var avgText = pollUnit_realTime[parmName];
				if(avgText){
					avgText = parmText +((parmName != "B01"&& parmName != "B01TOTAL")?"":"")+ "(" + avgText + ")";
				}
				else{
					avgText = parmText;
				}
				parmToChecksStr += $(parmToCheckDom[i]).val()+",";
				parmToCheckList.push({"name":parmName.toUpperCase(),"text":unitText,"parmText":parmText,"couText":couText,"avgText":avgText});
			}
			$.cookie("parmToChecksStr",parmToChecksStr,{expires:7});
			
			 var wwtpInfo = {
					 WWTPID:$scope.selectWWTP.SDEEXP_NO,
					 WWTP_NAME:$scope.selectWWTP.SDENAME,
					 MN0:$scope.selectWWTP.MN0,
					 MN1:$scope.selectWWTP.MN1,
					 SC0:$scope.selectWWTP.SC0,
					 SC1:$scope.selectWWTP.SC1
				 };
			 var wwtpReportParm = angular.extend(wwtpInfo,{parmToChecksStr:parmToChecksStr,parmToCheckList:parmToCheckList});
			
			return wwtpReportParm;
		}
		
		function initParmSelected(){
			var parmToChecksStr = $.cookie("parmToChecksStr");
			if(parmToChecksStr){
				var parms = parmToChecksStr.split(",");
				for(var i=0;i<parms.length;i++){
					var parm = parms[i];
					$("input[name='parmToCheck'][value='"+parm+"']").attr("checked","checked");
				}
			}
			else{
				var parms = $("input[name='parmToCheck']");
				for(var i=0;i<parms.length;i++){
					if(i<=5){
						$(parms[i]).attr("checked","checked");
					}
					else{
						return;
					}
				}
			}
		}
		initParmSelected();
		
		// 界面上点击参数后，更新选择项，触发查询
		$scope.showDataChangeParm = function(){
			noticeParmChange();
		}
		
		// 选择污水处理厂
		$scope.showData = function(obj){
			$scope.selectWWTP = obj;
			noticeParmChange();
			$("#wwtplist .list").removeClass("selected");
			$("div.list[wwtpid='"+obj.SDEEXP_NO+"']").addClass("selected");
		}
		
		//相应获取参数的事件
		$scope.$on('askedDataPramChange', function(event, data) {  
			noticeParmChange();
	    });
		
		/**
		 * 通知参数站点发生变化
		 */
		function noticeParmChange(){
			$scope.reportParms = getReportParms();
			$scope.$emit('dataPramChange', $scope.reportParms); 
		}
		
		// 如果缓存中有数据，直接从缓存中取列表数据
		if($wdp.viewValue.wsclcList != null && $wdp.viewValue.wsclcList.data != null && $wdp.viewValue.wsclcList.data.length > 0){
			$httpData.WsclcList = $wdp.viewValue.wsclcList;
			$scope.selectWWTP = $httpData.WsclcList.data[0];
			noticeParmChange();
		}
		else{
			$scope.queryList();
		}
		
		$scope.waterDataCommon = $waterDataCommon;
	});
	
	//地表水：统一的站点列表控制器，站点，报警信息，设备资产管理，运营管理，远程控制等模块使用
	SearchPanelController.controller('StationSearchController',function($scope,$rootScope,$itfreerHttp,$itfreer,
			$waterDataCommon,$httpData,$queryObj,$wdp,OperationStationJobService){
		
		$wdp.viewValue.wwtpDetailParm = {};
		
		$scope.xzqh = [];
		$scope.selectedXzqh={};
		OperationStationJobService.postQuery("/Operation/getXZQH.do",{}).then(function(data){
			$scope.xzqh =  data.data;
			if($scope.xzqh.length>0){
				$scope.selectedXzqh=$scope.xzqh[0];
				$scope.queryStation();
			}
		});
		$scope.toggleXzqh = function(row){
			if($scope.selectedXzqh==row) return;
			
			$scope.selectedXzqh=row;
			$scope.queryStation();
		}
		$scope.parmListShow = false;
		$scope.selectedStation = {};
		
		//查询站点
		$scope.queryStation=function(){
			var code = $scope.selectedXzqh.S_DOMAINCODE;
			if(code=='00'){
				delete $scope.queryObj.STATION_ID_LIKE; 
			}else{
				$scope.queryObj.STATION_ID_LIKE = code;
			}
				
			var waterType = getWaterType();
			$scope.queryObj.WATER_TYPE = waterType;
			$scope.queryObj.BUILD_STATUS='0';
				
			$waterDataCommon.getPageRows("/OnlineMonitor/station.do","stationList",$scope.queryObj,10,1,function(data){
				updateWWTPParm(data);
			});
		};
		
		//选择某个站点
		$scope.selectStation = function(curRow){
			$scope.selectedStation = curRow;
			$wdp.viewValue.wwtpDetailParm = {STATION_ID:curRow.CODE,STATION_NAME:curRow.NAME,DEVICE_NUM:curRow.DEVICE_NUM};
			//noticeParmChange();
		}		
		
		function updateWWTPParm(data){
			 $wdp.viewValue.stationList = data;
			 var selectStationId = null;
			 
			 if($wdp.viewValue.wwtpDetailParm){
				 selectStationId = $wdp.viewValue.wwtpDetailParm.STATION_ID;
			 }
			 
			 if(data.data.length > 0){
				 if(selectStationId){
					 for(var i in data.data){
						 var dataItem = data.data[i];
						 if(dataItem.CODE == selectStationId){
							 $scope.selectStation(dataItem);
						 }
					 }
				 }
				 else{
					 $scope.selectStation(data.data[0]);
				 }
			 }
		}

		$scope.queryObj.companyName = "全部";
		
		$scope.changeStationStatus = function(status){
			if($scope.queryObj.stationStatus == status){
				$scope.queryObj.stationStatus = "";
			}
			else{
				$scope.queryObj.stationStatus = status;
			}
			
			$scope.queryStation();
		}
		
		/**
		 * 选择企业
		 */
		$scope.changeCompany = function(company){
			$scope.queryObj.companyCode = company.companyCode;
			$scope.queryObj.companyName = company.companyName
			$scope.queryStation();
		}
		
		// 如果有缓存，则使用缓存中的数据
		if($wdp.viewValue.stationList != null && $wdp.viewValue.stationList.data != null && $wdp.viewValue.stationList.data.length > 0){
			$httpData.stationList = $wdp.viewValue.stationList;
			updateWWTPParm($httpData.stationList);
		}
		else{
			$scope.queryStation();
		}
		
		if($wdp.viewValue.wwtpDetailParmWatch){
			$wdp.viewValue.wwtpDetailParmWatch();
		}
		$wdp.viewValue.wwtpDetailParmWatch = $rootScope.$watch(function(){return $wdp.viewValue.wwtpDetailParm;},function(){
			$scope.wwtpDetailParm = $wdp.viewValue.wwtpDetailParm;
        },true);
		
		function noticeParmChange(){
		$scope.$emit('dataPramChange', $wdp.viewValue.wwtpDetailParm); 
	    }
		$scope.waterDataCommon = $waterDataCommon;
	});
	
	//地表水：实时数据，历史数据，报表模块的站点列表控制器，与StationSearchController相比，多了参数部分
	SearchPanelController.controller('StationListController',function($scope,$rootScope,$sce,$state,$waterDataCommon,
			$httpData,$queryObj,$wdp,OperationStationJobService){
		
		var pollUnit_report = {
			"011":"kg",
			"060":"kg",
			"B01":"",
			"B01TOTAL":"m³",
			"001":"",
			"101":"kg"
		};
		
		$scope.clearParmname = function(){
			var parmToCheckDom = $("input[name='parmToCheck']:checked");
			for(var i=0;i<parmToCheckDom.length;i++){
				$(parmToCheckDom[i]).removeAttr("checked");
			}
		}
		
		// 根据界面上勾选的参数，拼装参数，供前台表头显示，和后端数据查询
		function getReportParms(){
			
			var parmToCheckDom = $("input[name='parmToCheck']:checked");
			var parmToChecksStr = "";
			var parmToCheckList = [];
			var unit= {};
			
			for(var i=0;i<parmToCheckDom.length;i++){
				var parmCode = $(parmToCheckDom[i]).val();
				var parmText = $(parmToCheckDom[i]).attr("parmText");
				var parmUnit = $(parmToCheckDom[i]).attr("UNIT");
				
				var unitText = unit[parmCode];
				if(unitText){
					unitText = parmText +(isStatistics && (parmCode != "B01"&& parmCode != "B01TOTAL")?"排放量":"")+ "(" + unitText + ")";
				}
				else{
					unitText = parmText;
				}
				
				var couText = pollUnit_report[parmCode];
				if(couText){
					couText = parmText +((parmCode != "B01"&& parmCode != "B01TOTAL")?"排放量":"")+ "(" + couText + ")";
				}
				else{
					couText = parmText;
				}
				
				var avgText = "";
				if(parmUnit){
					avgText = parmText + "(" + parmUnit + ")";
				}
				else{
					avgText = parmText;
				}
				parmToChecksStr += $(parmToCheckDom[i]).val()+",";
				parmToCheckList.push({"name":parmCode.toUpperCase(),"text":unitText,"parmText":parmText,"couText":couText,"avgText":avgText});
			}
			$.cookie("parmToChecksStr",parmToChecksStr,{expires:7});
			var curRow = $scope.selectedStation;
			var wwtpReportParm = {
						parmToChecksStr:parmToChecksStr,
						parmToCheckList:parmToCheckList,
						STATION_ID:curRow.CODE,
						STATION_NAME:curRow.NAME,
						MN:curRow.DEVICE_NUM
					};
			return wwtpReportParm;
		}
		
		$scope.xzqh = [];
		$scope.selectedXzqh={};
		OperationStationJobService.postQuery("/Operation/getXZQH.do",{}).then(function(data){
			$scope.xzqh =  data.data;
			if($scope.xzqh.length>0){
				$scope.selectedXzqh=$scope.xzqh[0];
			}
		});
		$scope.toggleXzqh = function(row){
//			if($scope.selectedXzqh==row) return;
//			
//			$scope.selectedXzqh=row;
//			$scope.queryStation();
		}
		
		$scope.selectedStation = {};
		
		//查询站点
		$scope.queryStation=function(){
			var code = $scope.selectedXzqh.S_DOMAINCODE;
			if(code=='00'){
				delete $scope.queryObj.STATION_ID_LIKE; 
			}else{
				$scope.queryObj.STATION_ID_LIKE = code;
			}
				
			var waterType = getWaterType();
			$scope.queryObj.WATER_TYPE = waterType;
			$scope.queryObj.BUILD_STATUS='0';
				
			$waterDataCommon.getPageRows("/OnlineMonitor/station.do","stationList",$scope.queryObj,10,1,function(data){
				updateWWTPParm(data);
				 if(data.data.length > 0){
					 $scope.selectedStation = data.data[0];
				 }
			});
		};
		
		//选择某个站点
		$scope.selectStation = function(curRow){
			$scope.selectedStation = curRow;
			$waterDataCommon.getPageRows("/OnlineMonitor/getStationPollDict.do","stationPoll", {"STATION_ID":curRow.CODE},100,1,function(){
			},null,null,false);
		}
		
		// 界面上点击参数后，更新选择项，触发查询
		$scope.showDataChangeParm = function(){
			noticeParmChange();
		}
		
		//站点参数加载完成执行
		$scope.pollLoadFinish = function(){
			noticeParmChange();
		}
		
		//相应获取参数的事件
		$scope.$on('askedDataPramChange', function(event, data) {  
			noticeParmChange();
	    });
		
		/**
		 * 通知参数站点发生变化
		 */
		function noticeParmChange(){
			$scope.reportParms = getReportParms();
			$scope.$emit('dataPramChange', $scope.reportParms); 
		}
		
		function updateWWTPParm(data){
			$wdp.viewValue.stationList = data;
			if(data && data.data && data.data.length){
				var curRow = data.data[0];
				$scope.selectStation(curRow);
			}
		}
		
		if($wdp.viewValue.stationList != null && $wdp.viewValue.stationList.data != null && $wdp.viewValue.stationList.data.length > 0){
			$httpData.stationList = $wdp.viewValue.stationList;
			updateWWTPParm($httpData.stationList);
		}
		else{
			$scope.queryStation();
		}
		
		$scope.queryObj.companyName = "全部";
		function getCompany(){
			$waterDataCommon.getPageRows("/OnlineMonitor/wsclc.do","companyList",{"pollType":getWaterType()},100,1,function(d){
				if(d){
					$scope.companyList = d.data;
					
					$("a.zs-ddl").click(function() {
						$(this).next(".zs-ddl-contain").show("fast");
					});
					$(".zs-ddl-contain").find(".close").click(function(){
						$(this).parents(".zs-ddl-contain").hide("fast");
					})
					$(".zs-ddl-contain .list").niceScroll();
				}
			})
		}
		getCompany();
		
		$scope.changeStationStatus = function(status){
			if($scope.queryObj.stationStatus == status){
				$scope.queryObj.stationStatus = "";
			}
			else{
				$scope.queryObj.stationStatus = status;
			}
			
			$scope.queryStation();
		}
		
		/**
		 * 选择企业
		 */
		$scope.changeCompany = function(company){
			$scope.queryObj.companyCode = company.SDEEXP_NO;
			$scope.queryObj.companyName = company.SDENAME
			$(".zs-ddl-contain").hide("fast");
			$scope.queryStation();
		}
		
		$scope.waterDataCommon = $waterDataCommon;
	});
	
}(window, angular));	